<template>
  <div class="aiimgsplan clearfix" ref="aiimgsplan">
    <div class="logocontent">
      <svg-icon icon-class="uav2" style="font-size: 60px"></svg-icon>
      <div class="logotitle">
        <div class="logotitle_nest">位置：{{ address }}</div>
        <div class="logotitle_task">
          单号：{{ problemData.problemShowName }}
        </div>
      </div>
      <div class="btns" v-show="isMobileOrPc">
        <div class="btn">
          <el-tooltip
            class="item"
            effect="dark"
            content="复制链接"
            placement="bottom"
          >
            <svg-icon icon-class="copy" @click="copyUrl()" />
          </el-tooltip>
        </div>
        <div class="btn">
          <el-tooltip
            class="item"
            effect="dark"
            content="下载图片"
            placement="bottom"
          >
            <svg-icon icon-class="download" @click="downs()" />
          </el-tooltip>
        </div>
      </div>
    </div>
    <div class="container">
      <div
        class="content"
        ref="content"
        v-show="MobileMapPicTabFlag || isMobileOrPc"
      >
        <canvas id="canvas" ref="canvas"></canvas>
        <div class="line" v-if="markPicList.length > 1"></div>
        <div class="timelines" v-if="markPicList.length > 1">
          <div
            class="item"
            v-for="(item, index) in markPicList"
            :key="index"
            @click="changePhoto(item)"
          >
            <div
              class="slot"
              :class="[
                { hasmark: item.tags.length > 0 },
                { active: picCompInfo.photoCode == item.photo_id },
              ]"
            ></div>
            <div
              class="txt"
              :class="{ active: picCompInfo.photoCode == item.photo_id }"
            >
              <span>{{ timeAgo(item.photo_time) }}</span>
              <span>{{ item.photo_time | timeFilter }}</span>
            </div>
          </div>
        </div>
        <div class="zoom_wrap">
          <div class="btn_zoom" @click="zoomCanvas(0.2)">+</div>
          <div class="btn_zoom" @click="zoomCanvas(-0.2)">-</div>
        </div>
      </div>
      <div class="content-right">
        <div class="mymap" v-show="!MobileMapPicTabFlag || isMobileOrPc">
          <MyMap
            ref="mapcomp"
            :picCompInfo="picCompInfo"
            :airlineInfo="airlineInfo"
          ></MyMap>
        </div>
        <div class="txtbox">
          <p>拍摄航线：{{ problemRecord["projectName"] }}</p>
          <p>拍摄时间：{{ photo_time ? photo_time : mark.createTime }}</p>

          <div
            v-show="!isMobileOrPc"
            @click="toaddress = true"
            class="qudaohang"
          >
            去导航<i class="el-icon-d-arrow-right"></i>
          </div>
        </div>
        <div class="maptab" v-if="!isMobileOrPc">
          <div class="tab" @click="chakanDitu" v-show="MobileMapPicTabFlag">
            <img src="@/views/components/SharedMap/imgs/tab-map.png" alt="" />
            <span>查看地图</span>
          </div>
          <div
            class="tab"
            @click="MobileMapPicTabFlag = !MobileMapPicTabFlag"
            v-show="!MobileMapPicTabFlag"
          >
            <img src="@/views/components/SharedMap/imgs/tab-img.png" alt="" />
            <span>查看图片</span>
          </div>
        </div>
      </div>
      <div class="navlistBox" v-show="toaddress">
        <div class="maskplan" @click="toaddress = false"></div>
        <div class="navlist">
          <div @click="guide('gd')">高德地图</div>
          <div @click="guide('bd')">百度地图</div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import store from "@/store";
import { getProblem, problemHistory, markProjection } from "@/api/censuisdata";
import { fabric } from "fabric";
import MyMap from "./components/SharedMap/mymap.vue";
import { timeago } from "@/utils/formatTime";
import { wgs84Togcj02, gcj02tobd09 } from "@/utils/index.js";

import { addUrlToken } from "@/utils/allTool";
export default {
  components: {
    MyMap,
  },
  computed: {},
  filters: {
    timeFilter(text) {
      var a = text.split(" ");
      // if(a[1]){
      //   a= text.split(' ')[1].slice(0,5)
      // }else{
      //   a = a[0]
      // }
      a = a[0];
      return a;
    },
    statusTextFilter(status) {
      const statusTextMap = {
        10: "上报",
        20: "受理",
        30: "办理",
        32: "分拨",
        36: "回退",
        37: "协同审核",
        38: "协同反馈",
        39: "督办",
        40: "结案",
        50: "反馈",
        1: "办理",
        8: "新增",
        61: "受理",
        63: "自动签收",
        21: "转交",
        31: "结案",
        66: "转为无效事件",
      };
      return statusTextMap[status];
    },
    suggestionTextFilter(text) {
      try {
        var a = JSON.parse(text);
        console.log(a);
        if (typeof a == "object") {
          if (a instanceof Array) {
            return a[0]["dealDescription"];
          } else if (a instanceof Object) {
            return a["dealDescription"];
          } else {
            return null;
          }
        }
      } catch (e) {
        return text;
      }
    },
  },
  data() {
    return {
      my_canvas: "",
      panning: false,
      isLoading: false,
      SceneRows: null, //获取场景标签
      mapInfo: null,
      mapInfo_yes: null,
      CurrentPageSize: 12,
      nest_name: "",
      flight_record_name: "",
      picCompInfo: "",
      problemData: "",
      airlineInfo: "",
      mark: "",
      marks: [],
      pmarks: [],
      airline_name: "",
      address: "",
      videoSrc: "",
      player: "",
      operLogs: [],
      dialogVisible: false,
      formLabe: {
        dept: "",
        person: "",
        info: "",
      },
      person_options: [],
      photo_time: "",
      problemRecord: "",
      curImageUrl: "",
      markPicList: [],
      isMobileOrPc: true,
      toaddress: false,
      MobileMapPicTabFlag: 1,
    };
  },

  methods: {
    chakanDitu() {
      this.$refs.mapcomp.invalidateSize();
      this.MobileMapPicTabFlag = !this.MobileMapPicTabFlag;
    },
    //导航
    guide(signMap) {
      let self = this;

      var lng = self.mark.markPositionLongitude;
      var lat = self.mark.markPositionLatitude;

      if (lng && lat) {
        if (signMap == "gd") {
          lng = wgs84Togcj02(
            self.mark.markPositionLongitude,
            self.mark.markPositionLatitude
          )[0];
          lat = wgs84Togcj02(
            self.mark.markPositionLongitude,
            self.mark.markPositionLatitude
          )[1];
          // 高德地图
          if (self.customBrowserVersion().android) {
            window.location.href =
              "androidamap://viewMap?sourceApplication=appname&poiname=" +
              self.address +
              "&lat=" +
              lat +
              "&lon=" +
              lng +
              "&dev=0";
            //判断是否跳转
            setTimeout(function () {
              let hidden =
                window.document.hidden ||
                window.document.mozHidden ||
                window.document.msHidden ||
                window.document.webkitHidden;
              if (typeof hidden == "undefined" || hidden == false) {
                //调用高德地图
                window.location.href =
                  "https://uri.amap.com/marker?position=" +
                  lng +
                  "," +
                  lat +
                  "&name=" +
                  self.address;
              }
            }, 2000);
          } else if (self.customBrowserVersion().ios) {
            window.location.href =
              "iosamap://viewMap?sourceApplication=appname&poiname=" +
              self.address +
              "&lat=" +
              lat +
              "&lon=" +
              lng +
              "&dev=0";
            //判断是否跳转
            setTimeout(function () {
              let hidden =
                window.document.hidden ||
                window.document.mozHidden ||
                window.document.msHidden ||
                window.document.webkitHidden;
              if (typeof hidden == "undefined" || hidden == false) {
                //调用高德地图
                window.location.href =
                  "https://uri.amap.com/marker?position=" +
                  lng +
                  "," +
                  lat +
                  "&name=" +
                  self.address;
              }
            }, 2000);
          }
          setTimeout(function () {
            self.toaddress = false;
          }, 2000);
        } else if (signMap == "bd") {
          lng = gcj02tobd09(
            wgs84Togcj02(
              self.mark.markPositionLongitude,
              self.mark.markPositionLatitude
            )[0],
            wgs84Togcj02(
              self.mark.markPositionLongitude,
              self.mark.markPositionLatitude
            )[1]
          )[0];
          lat = gcj02tobd09(
            wgs84Togcj02(
              self.mark.markPositionLongitude,
              self.mark.markPositionLatitude
            )[0],
            wgs84Togcj02(
              self.mark.markPositionLongitude,
              self.mark.markPositionLatitude
            )[1]
          )[1];

          // 百度地图
          if (self.customBrowserVersion().android) {
            //安卓操作系统
            let d = new Date();
            let t0 = d.getTime();
            window.location.href =
              "androidamap://viewMap?sourceApplication=appname&poiname=" +
              self.address +
              "&lat=" +
              lat +
              "&lon=" +
              lng +
              "&dev=0";
            //由于打开需要1～2秒，利用这个时间差来处理－－打开app后，返回h5页面会出现页面变成app下载页面，影响用户体验
            var delay = setInterval(function () {
              var d = new Date();
              var t1 = d.getTime();
              if (t1 - t0 < 3000 && t1 - t0 > 2000) {
                window.location.href =
                  "http://api.map.baidu.com/marker?location=" +
                  lat +
                  "," +
                  lng +
                  "&title=" +
                  self.address +
                  "&content=景点&output=html&src=webapp.baidu.openAPIdemo";
              }
              if (t1 - t0 >= 3000) {
                clearInterval(delay);
              }
            }, 1000);
          }
          if (self.customBrowserVersion().ios) {
            //ios操作系统
            let d = new Date();
            let t0 = d.getTime();
            window.location.href =
              "iosamap://viewMap?sourceApplication=appname&poiname=" +
              self.address +
              "&lat=" +
              lat +
              "&lon=" +
              lng +
              "&dev=0";
            //由于打开需要1～2秒，利用这个时间差来处理－－打开app后，返回h5页面会出现页面变成app下载页面，影响用户体验
            let delay = setInterval(function () {
              var d = new Date();
              var t1 = d.getTime();
              if (t1 - t0 < 3000 && t1 - t0 > 2000) {
                window.location.href =
                  "http://api.map.baidu.com/marker?location=" +
                  lat +
                  "," +
                  lng +
                  "&title=" +
                  self.address +
                  "&content=地址&output=html&src=webapp.baidu.openAPIdemo";
              }
              if (t1 - t0 >= 3000) {
                clearInterval(delay);
              }
            }, 1000);
          }
          setTimeout(function () {
            self.toaddress = false;
          }, 2000);
        }
      } else {
        alert("暂不知道该景区位置");
        self.toaddress = false;
      }
    },
    //区分设备
    customBrowserVersion() {
      var u = navigator.userAgent;
      return {
        trident: u.indexOf("Trident") > -1, //IE内核
        presto: u.indexOf("Presto") > -1, //opera内核
        webKit: u.indexOf("AppleWebKit") > -1, //苹果、谷歌内核
        gecko: u.indexOf("Gecko") > -1 && u.indexOf("KHTML") == -1, //火狐内核
        mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
        ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
        android: u.indexOf("Android") > -1 || u.indexOf("Adr") > -1, //android终端
        iPhone: u.indexOf("iPhone") > -1, //是否为iPhone或者QQHD浏览器
        iPad: u.indexOf("iPad") > -1, //是否iPad
        webApp: u.indexOf("Safari") == -1, //是否web应用程序，没有头部与底部
        weixin: u.indexOf("MicroMessenger") > -1, //是否微信 （2015-01-22新增）
        qq: u.match(/\sQQ/i) == " qq", //是否QQ
        isBaidu: u.indexOf("baiduboxapp") !== -1, //是否为百度浏览器
        isqqBrowser: u.indexOf("mqqbrowser") !== -1, //是否为qq浏览器
        isWxBrowser: u.indexOf("micromessenger") !== -1, //是否为微信浏览器
        isUc: u.indexOf("ucbrowser") !== -1, //是否为uc浏览器
      };
    },

    _isMobile() {
      let flag = navigator.userAgent.match(
        /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
      );
      return flag;
    },
    fetchData() {
      problemHistory({
        markPositionLongitude: this.mark.markPositionLongitude,
        markPositionLatitude: this.mark.markPositionLatitude,
        photo_time: this.photo_time,
        sceneName: this.mark["tagLabel"],
        photo_id: this.mark["photoCode"],
      }).then((res) => {
        if (res.data) {
          this.markPicList = res.data;
        } else if (this.problemData["problemCode"] == "4717317059661271042") {
          this.markPicList = ProblemHistory1;
        }
      });
    },
    changePhoto(item) {
      this.picCompInfo = {
        photoCode: item["photo_id"],
        exif_xmp: item["exif_xmp"],
      };
      this.photo_time = item["photo_time"];
      this.problemRecord["projectName"] = item["flight_record_name"];
      if (item["tags"].length > 0) {
        this.pmarks = item["tags"];
        this.SetImage(item["photo_url"]);
      } else {
        markProjection({
          position: [
            this.mark["markPositionLongitude"],
            this.mark["markPositionLatitude"],
          ],
          photo_info_code: item["photo_id"],
        }).then((res) => {
          var point = res.data;
          console.log(point);
          if (point[0] != -1) {
            var obj = {
              points: [
                [point[0] - 300, point[1] - 300],
                [point[0] + 300, point[1] + 300],
              ],
              tag_name: "",
            };
            this.pmarks = [obj];
          } else {
            this.pmarks = [];
          }

          this.SetImage(item["photo_url"]);
        });
      }
    },
    timeAgo(val) {
      return timeago(val);
    },
    handleResize() {
      if (this.my_canvas && this.isMobileOrPc) {
        var scaleMultiplier =
          this.$refs.content.offsetWidth / this.my_canvas.width;
        // var objects = this.my_canvas.getObjects();
        // for (var i in objects) {
        //     objects[i].scaleX = objects[i].scaleX * scaleMultiplier;
        //     objects[i].scaleY = objects[i].scaleY * scaleMultiplier;
        //     objects[i].left = objects[i].left * scaleMultiplier;
        //     objects[i].top = objects[i].top * scaleMultiplier;
        //     objects[i].setCoords();
        // }

        this.my_canvas.setWidth(this.$refs.content.offsetWidth);
        this.my_canvas.setHeight(this.$refs.content.offsetHeight);
        this.my_canvas.renderAll();
        this.my_canvas.calcOffset();
      }
    },
    initCanvas() {
      // 初始化Canvas
      var _this = this;
      var initcanvas = this.$refs.canvas;
      var canvasWidth = this.$refs.content.offsetWidth;
      var canvasHeight = this.$refs.content.offsetHeight;
      // 1. 实例化canvas 画布
      var canvas = new fabric.Canvas(initcanvas, {
        width: canvasWidth,
        height: canvasHeight,
        selection: false,
        crossOrigin: "anonymous",
      });
      // 2. 设置背景图片作为底图（这里导入图片使用require，不要 使用 '../../' 方式）
      // canvas.width / 4764  （4764 是我底图图片宽度）
      // canvas.height / 3367 （3367 是我 底图图片宽度）
      canvas.originX = "center";
      canvas.originY = "center";
      var drawX = 0,
        drawY = 0;
      var lastMovePoint = null;
      var drawstarted = false; //判断是否是绘制rect开始
      var clickstarted = false; //clickdown开始
      var startW = false;
      var currentSquare;
      var isChange = false;
      var canvasWrapper = _this.$refs.aiimgsplan;
      canvasWrapper.tabIndex = 1000;

      canvasWrapper.addEventListener(
        "keydown",
        function (e) {
          var e = e ? e : window.event;
          var currKey = e.keyCode || e.which || e.charCode;
          if (currKey == 87) {
            startW = true;
          }
        },
        false
      );

      canvas.on("mouse:down", (e) => {
        if (!e.target && _this.AiMode && startW) {
          clickstarted = true;
          var mouse = e.absolutePointer;
          drawX = mouse.x;
          drawY = mouse.y;
        } else if (!e.target) {
          _this.panning = true;
          lastMovePoint = e.absolutePointer;
        }
      });

      canvas.on("mouse:up", (e) => {
        clickstarted = false;
        startW = false;
        _this.panning = false;
        lastMovePoint = null;
      });

      // 添加标签
      window.notice = function (data, id) {
        var label = data;
        var labelId = id;
        console.log(label);

        isChange = true;
        isChange_label = true;
        console.log(isChange);
        var squareid = currentSquare.metaData.id;
        _this.removeTextBySquareId(squareid, canvas);
        var text = new fabric.Text(label, {
          fontSize: 12,
          originX: "left",
          originY: "top",
          padding: 5,
          backgroundColor: "rgba(255, 0, 0, 0.6)",
          fill: "rgba(255,255,255,1.0)",
          top: currentSquare.top - 15,
          left: currentSquare.left + 1,
          evented: false,
          metaData: {
            id: squareid,
            tagId: labelId,
            type: "text",
          },
        });
        canvas.add(text);
        canvas.renderAll();
      };
      // PC画布事件
      canvas.on("mouse:move", function (e) {
        // 平移
        if (_this.panning && e && e.e) {
          if (e.e.movementX) {
            var delta = new fabric.Point(e.e.movementX, e.e.movementY);
            canvas.relativePan(delta);
          } else {
            var padDelta = new fabric.Point(
              e.absolutePointer.x - lastMovePoint.x,
              e.absolutePointer.y - lastMovePoint.y
            );
            canvas.relativePan(padDelta);
            lastMovePoint = e.absolutePointer;
          }
        } else if (clickstarted) {
          var mouse = e.absolutePointer;
          var x = Math.min(drawX, mouse.x),
            y = Math.min(drawY, mouse.y);
          var w = Math.abs(mouse.x - drawX),
            h = Math.abs(mouse.y - drawY);
          if (!w || !h) {
            return false;
          }
          canvas.renderAll();
        }
      });
      //鼠标滚动画布放大缩小
      canvas.on("mouse:wheel", function (e) {
        var zoom = (e.e.deltaY > 0 ? -0.5 : 0.5) + canvas.getZoom();
        zoom = Math.max(1, zoom); //最小为原来的1/10
        zoom = Math.min(10, zoom); //最大是原来的3倍
        var zoomPoint = new fabric.Point(e.e.offsetX, e.e.offsetY);
        canvas.zoomToPoint(zoomPoint, zoom);
        //rect边框自适应缩放
        canvas.forEachObject(function (obj) {
          if (obj.strokeWidth) {
            obj.set({
              strokeWidth: 2 / zoom,
            });
          } else if (obj._objects[0].strokeWidth) {
            obj._objects[0].set({
              strokeWidth: 2 / zoom,
            });
          }
        });
        canvas.renderAll();
      });

      canvas.on("object:modified", function (e) {
        console.log("object:modified");
        isChange = true;
        isChange_rect = true;
      });

      canvas.on("object:moving", function (e) {
        var canvasContainer2 =
          document.getElementsByClassName("canvas-container")[0];
        var deletebtnName2 = document.getElementsByClassName("deleteBtn")[0];
        if (deletebtnName2) {
          canvasContainer2.removeChild(deletebtnName2);
        }

        var text = _this.getTextBySquareId(e.target.metaData.id, canvas);
        if (text) {
          text.set("top", e.target.top - 15).set("left", e.target.left + 1);
        }
        var json = canvas.toJSON();
        var backimg = json.backgroundImage;
        if (e.target) {
          var square = canvas.getActiveObject();
          var x = square.left < backimg.left ? backimg.left : square.left;
          x =
            x + square.width > backimg.left + backimg.width * backimg.scaleX
              ? backimg.left + backimg.width * backimg.scaleX - square.width
              : x;
          var y = square.top < backimg.top ? backimg.top : square.top;
          y =
            y + square.height > backimg.top + backimg.height * backimg.scaleY
              ? backimg.top + backimg.height * backimg.scaleY - square.height
              : y;
          square.set("top", y).set("left", x);
          canvas.renderAll();
        }
        isChange = true;
        isChange_rect = true;
      });

      canvas.on("object:scaling", function () {
        console.log("object:scaling");
        var json = canvas.toJSON();
        var backimg = json.backgroundImage;
        let square = canvas.getActiveObject();
        let x = square.left < backimg.left ? backimg.left : square.left;
        let y = square.top < backimg.top ? backimg.top : square.top;
        let w = square.width * square.scaleX;
        let h = square.height * square.scaleY;

        w =
          square.left + w > backimg.left + backimg.width * backimg.scaleX
            ? backimg.left + backimg.width * backimg.scaleX - square.left
            : w;
        h =
          square.top + h > backimg.top + backimg.height * backimg.scaleY
            ? backimg.top + backimg.height * backimg.scaleY - square.top
            : h;
        square
          .set("scaleX", 1.0)
          .set("scaleY", 1.0)
          .set("top", y)
          .set("left", x)
          .set("width", w)
          .set("height", h);
        canvas.renderAll();
      });

      return canvas;
    },

    // 去文本标注
    removeTextBySquareId(id, canvas) {
      var json = canvas.getObjects();
      for (var i = 0; i < json.length; i++) {
        if (json[i].metaData) {
          if (json[i].metaData.id == id && json[i].metaData.type == "text") {
            console.log(json[i]);
            canvas.remove(json[i]);
            break;
          }
        }
      }
    },

    // 添加文本标注
    getTextBySquareId(id, canvas) {
      // console.log(canvas.getObjects());
      var json = canvas.getObjects();
      for (let i = 0; i < json.length; i++) {
        if (json[i].metaData) {
          if (json[i].metaData.id == id && json[i].metaData.type == "text") {
            return json[i];
          }
        }
      }
      return false;
    },

    SetImage(url) {
      console.log("调用画布");

      this.curImageUrl = url;
      var that = this;
      //重置canvas，解决缩放，平移导致的位置不对问题
      if (!this.isMobileOrPc) {
        that.my_canvas.setZoom(1.3);
      } else {
        that.my_canvas.setZoom(1);
      }

      that.my_canvas.absolutePan(new fabric.Point(0, 0));

      that.my_canvas.renderAll();

      var img_ = new Image();
      img_.setAttribute("crossOrigin", "anonymous");
      console.log(url);

      img_.src = addUrlToken(url);

      //清空画布
      that.my_canvas.clear();

      img_.onload = function () {
        var scale = that.my_canvas.height / img_.height;
        console.log("scale:" + scale);
        scale = parseFloat(scale.toFixed(3));
        var left = (that.my_canvas.width - img_.width * scale) / 2;
        var top = 0;
        console.log(img_.src);
        that.my_canvas.setBackgroundImage(
          img_.src,
          that.my_canvas.renderAll.bind(that.my_canvas),
          {
            originX: "left",
            originY: "top",
            left: left,
            top: top,
            scaleX: scale,
            scaleY: scale,
            crossOrigin: "anonymous",
          }
        );

        if (that.pmarks.length > 0) {
          for (var i = 0; i < that.pmarks.length; i++) {
            that.pmarks[i]["tagLabel"] = that.pmarks[i]["tag_name"];
            that.GetAnnotations_yes(that.pmarks[i], scale, left, top);
          }
        } else if (that.marks.length > 0) {
          for (var i = 0; i < that.marks.length; i++) {
            that.marks[i]["tagLabel"] = that.mark["tagLabel"];
            if (that.marks[i]["photoCode"] == that.picCompInfo["photoCode"]) {
              that.GetAnnotations_yes(that.marks[i], scale, left, top);
            }
          }
        }
        console.log("marks");
        console.log(that.pmarks);
        that.$refs.mapcomp.getMap();
      };
    },
    GetAnnotations_yes(mark, scale1, left1, top1) {
      var _this = this;
      if (mark["points"].length > 2) {
        var box_type = "polygon";
      } else {
        var box_type = "rect";
      }

      if (box_type == "rect") {
        var left = mark["points"][0][0] * scale1 + left1;
        var top = mark["points"][0][1] * scale1 + top1;
        var width = (mark["points"][1][0] - mark["points"][0][0]) * scale1;
        var height = (mark["points"][1][1] - mark["points"][0][1]) * scale1;
        var iid = _this.newGuid();
        var square = new fabric.Rect({
          width: width,
          height: height,
          originX: "left",
          originY: "top",
          left: left,
          top: top,
          fill: "rgba(0,0,0,0)",
          stroke: "#ec1518",
          strokeWidth: 2,
          evented: false,
          metaData: {
            id: iid,
            markId: mark["markId"],
            type: "rect",
          },
        });
      } else if (box_type == "polygon") {
        var positions = [];

        var a1 = 9999,
          a2 = 9999;

        for (var j = 0; j < mark["points"].length; j++) {
          if (a1 > mark["points"][j][0]) a1 = mark["points"][j][0];
          if (a2 > mark["points"][j][1]) a2 = mark["points"][j][1];
          positions.push({
            x: mark["points"][j][0] * scale1 + left1,
            y: mark["points"][j][1] * scale1,
          });
        }

        var left = a1 * scale1 + left1;
        var top = a2 * scale1 + top1;
        var iid = _this.newGuid();
        var square = new fabric.Polygon(positions, {
          fill: "rgba(0,0,0,0)",
          stroke: "#ec1518",
          strokeWidth: 2,
          evented: false,
          lockMovementX: true, //禁止元素移动，但是可以选中
          lockMovementY: true,
          metaData: {
            id: iid,
            markId: mark["markId"],
            type: "polygon",
          },
        });
      }
      square.setControlVisible("mtr", false);
      if (mark["tagLabel"]) {
        var text = new fabric.Text(mark["tagLabel"], {
          fontSize: 12,
          originX: "left",
          originY: "top",
          padding: 5,
          backgroundColor: "rgba(255, 0, 0, 0.6)",
          fill: "rgba(255,255,255,1.0)",
          top: top - 15,
          left: left + 1,
          evented: false,
          metaData: {
            id: iid,
            type: "text",
          },
        });
        _this.my_canvas.add(text);
      } else {
        square.strokeDashArray = [6, 6];
      }

      _this.my_canvas.add(square);
      if (!this.isMobileOrPc) {
        _this.my_canvas.absolutePan({
          x: square.left - _this.my_canvas.width / 2,
          y: square.top - _this.my_canvas.height / 2,
        });
      }
      _this.my_canvas.renderAll();
    },

    getColorByBoxType(type) {
      if (type == "broke") {
        return "#0055ff";
      } else if (type == "rubbish") {
        return "#aa55ff";
      } else if (type == "farmland") {
        return "#55ff7f";
      } else if (type == "buildings") {
        return "#ff5500";
      } else if (type == "vendor") {
        return "#00ffff";
      } else if (type == "trunk") {
        return "#d51ac3";
      } else if (type == "strawBurning") {
        return "#ec1518";
      } else if (type == "crowded") {
        return "#ffff00";
      } else if (type == "engineeringCar") {
        return "#ffd21c";
      } else if (type == "car") {
        return "#00aaff";
      } else if (type == "bus") {
        return "#ff9166";
      } else {
        return "#ffffff";
      }
    },
    newGuid() {
      var guid = "";
      for (var i = 1; i <= 32; i++) {
        var n = Math.floor(Math.random() * 16.0).toString(16);
        guid += n;
        if (i == 8 || i == 12 || i == 16 || i == 20) guid += "-";
      }
      return guid;
    },

    copyUrl() {
      var domUrl = document.createElement("input");
      domUrl.value = window.location.href;
      domUrl.id = "creatDom";
      document.body.appendChild(domUrl);
      domUrl.select(); // 选择对象
      document.execCommand("Copy"); // 执行浏览器复制命令
      let creatDom = document.getElementById("creatDom");
      creatDom.parentNode.removeChild(creatDom);
      this.$message({
        message: "复制成功",
        type: "success",
      });
    },
    downloadIamge(imgsrc, name) {
      //下载图片地址和图片名
      var that = this;
      var createBy = that.$store.getters.userName
        ? that.$store.getters.userName
        : "东南飞视";

      var text = new fabric.Text(createBy, {
        fontSize: 14,
        originX: "left",
        originY: "top",
        padding: 5,
        fill: "rgba(255,255,255,0.3)",
        top: that.my_canvas.vptCoords.tl.y + 20,
        left: that.my_canvas.vptCoords.tl.x + 40,
        evented: false,
        angle: 45,
      });
      that.my_canvas.add(text);
      var text1 = new fabric.Text(createBy, {
        fontSize: 14,
        originX: "left",
        originY: "top",
        padding: 5,
        fill: "rgba(255,255,255,0.3)",
        top: that.my_canvas.vptCoords.br.y - 60,
        left: that.my_canvas.vptCoords.br.x - 70,
        evented: false,
        angle: 45,
      });
      that.my_canvas.add(text1);

      var url = that.my_canvas.toDataURL("image/jpeg"); //得到图片的base64编码数据

      var a = document.createElement("a"); // 生成一个a元素
      var event = new MouseEvent("click"); // 创建一个单击事件
      a.download = name || "photo.png"; // 设置图片名称
      a.href = url; // 将生成的URL设置为a.href属性
      a.dispatchEvent(event); // 触发a的单击事件
    },
    downs() {
      // 主要是为了名字不重复
      var name = new Date().getTime();
      this.downloadIamge(this.curImageUrl, `${name}.png`);
    },

    zoomCanvas(val) {
      console.log("this.my_canvas", this.my_canvas);
      var zoom = val + this.my_canvas.getZoom();
      zoom = Math.max(1, zoom); //最小为原来的1/10
      zoom = Math.min(10, zoom); //最大是原来的3倍
      var zoomPoint = new fabric.Point(
        this.my_canvas.width / 2,
        this.my_canvas.height / 2
      );

      this.my_canvas.zoomToPoint(zoomPoint, zoom);
      //rect边框自适应缩放
      this.my_canvas.forEachObject(function (obj) {
        if (obj.strokeWidth) {
          obj.set({
            strokeWidth: 2 / zoom,
          });
        } else if (obj._objects[0].strokeWidth) {
          obj._objects[0].set({
            strokeWidth: 2 / zoom,
          });
        }
      });
      this.my_canvas.renderAll();
    },
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.handleResize);
  },
  mounted() {
    console.log(this.$route.meta.title);
    var config = store.getters.kanBanConfig;
    var $favicon = document.querySelector('link[rel="icon"]');
    if ($favicon !== null) {
      $favicon.href = config.favicon_logo
        ? config.favicon_logo
        : "https://fsimage.guihuao.com/oper_log/miniapp/fc5cc2fae62be9ddf0e8d5333a317968.png";
    } else {
      $favicon = document.createElement("link");
      $favicon.rel = "icon";
      $favicon.href = config.favicon_logo
        ? config.favicon_logo
        : "https://fsimage.guihuao.com/oper_log/miniapp/fc5cc2fae62be9ddf0e8d5333a317968.png";
      document.head.appendChild($favicon);
    }
    var query = this.$route.query;
    var problemCode = query.problemCode;
    var title = query.title;
    if (title) {
      document.title = title;
    }
    // 根据不同路由跳转不同页面
    if (this._isMobile()) {
      console.log("手机端");
      this.isMobileOrPc = false;
      // this.$route.meta.title='分享问题详情';
      window.document.title = "分享问题详情";
    } else {
      console.log("pc端");
      this.isMobileOrPc = true;
    }

    window.addEventListener("resize", this.handleResize);
    this.handleResize();

    getProblem({
      problemCode: problemCode,
    }).then((res) => {
      console.log(res.data);

      this.problemData = res.data;

      this.my_canvas = this.initCanvas();

      if (this.problemData["marks"].length == 0) {
        this.$notify.info({
          title: "提示",
          message: "该问题被删除",
          duration: 0,
          position: "top-left",
        });
        return false;
      } else {
        var src = this.problemData["marks"][0]["photoOssUrl"];
        var arr = src.split("?");
        src = arr[0];
        var newsrc = src.replace("https", "http");
        console.log(newsrc);
      }

      if (this.problemData["airline"]) {
        this.airline_name = this.problemData["airline"]["airline_name"];
        this.airlineInfo = {
          waypoints: this.problemData["airline"]["waypoints"],
        };
      }
      this.address = this.problemData["address"];
      this.picCompInfo = {
        latitude: this.problemData["lat"],
        longitude: this.problemData["lng"],
        photoCode: this.problemData["marks"][0]["photoCode"],
        exif_xmp: this.problemData["marks"][0]["photoExif"],
      };
      var time = this.problemData["marks"][0]["photoExif"]["photo_time"];
      this.photo_time = time.replace(":", "-").replace(":", "-");
      this.$refs.mapcomp.addSharedMarks([this.problemData["marks"][0]]);

      this.problemRecord = this.problemData["baseProblemFlightRecord"][0];

      this.mark = this.problemData["marks"][0];
      this.mark["tagLabel"] = this.problemData["sceneName"];
      this.marks = this.problemData["marks"];

      this.SetImage(newsrc);

      this.fetchData();
    });
  },
};
</script>

<style lang="scss" scoped>
::-webkit-scrollbar {
  /*滚动条整体样式*/
  width: 8px;
  /*高宽分别对应横竖滚动条的尺寸*/
  height: 1px;
}

::-webkit-scrollbar-thumb {
  /*滚动条里面小方块*/
  border-radius: 8px;
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  background: rgba(3, 71, 85, 0.8);
}

::-webkit-scrollbar-track {
  /*滚动条里面轨道*/
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  border-radius: 10px;
  background: rgba(255, 255, 255, 0.5);
}

::v-deep .el-timeline-item__timestamp {
  color: #0a95ff;
  font-size: 20px;
  margin-bottom: 10px;
}

::v-deep .el-timeline-item__tail {
  border-left: 2px solid #a2a4a8;
}

ul {
  padding: 0;
}

.aiimgsplan {
  position: fixed;
  top: 0;
  left: 0;
  overflow: hidden;
  width: 100%;
  height: 100%;
  outline: none;
  background-color: rgba(5, 34, 74, 0.95);
  color: #333333;

  .logocontent {
    width: 100%;
    // height: vh(60);
    display: flex;
    margin: vh(30) vw(40);
    color: white;

    .logo {
      width: vw(60);
      height: vh(60);
      background-image: url("http://guihuao.com/2021/Kanban/Ai/images/logo.png");
      background-size: cover;
    }

    .logotitle {
      font-size: 22px;
      margin-left: 15px;
      overflow: hidden;
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      .logotitle_nest {
        font-size: 20px;
        font-weight: 600;
      }

      .logotitle_task {
        font-size: 20px;
      }
    }

    .btns {
      position: absolute;
      right: 50px;
      top: 10px;
      width: 250px;
      margin: 20px auto;
      height: 60px;
      display: flex;

      .btn {
        width: 40px;
        height: 40px;
        margin-left: 10px;
        font-size: 30px;
        text-align: center;
        color: white;
        line-height: 40px;
        cursor: pointer;
        position: relative;

        &.item {
          font-size: 20px;
        }

        .red {
          position: absolute;
          top: -1px;
          right: 0px;
          width: 16px;
          height: 16px;
          line-height: 16px;

          border-radius: 8px;
          background-color: red;
          font-size: 13px;
        }
      }

      > div:hover {
        background-color: rgba(243, 243, 243, 0.2);
      }
    }
  }

  .container {
    width: 100%;
    height: calc(100% - vh(60));
    display: flex;

    .content {
      width: vw(1100);
      height: vh(900);
      position: relative;
      display: flex;
      background-color: #00232d;
      box-shadow: 0 0 5px rgb(255 255 255 / 50%);
      margin-top: 0px;
      margin-left: 40px;

      #canvas {
        width: 100%;
        height: 100%;
      }

      .line {
        position: absolute;
        right: vw(155);
        top: 0;
        width: 2px;
        height: 100%;
        z-index: 1;
        background-color: rgba(243, 243, 243, 0.7);
      }

      .timelines {
        position: absolute;
        width: 160px;
        right: 10px;
        top: 0;
        padding: 0 10px;
        height: 100%;
        overflow-y: auto;
        z-index: 2;

        // border-left: 2px solid rgba(243,243,243,0.7);
        &:hover {
          background-color: rgba(0, 0, 0, 0.3);
        }

        .item {
          color: white;
          display: flex;
          position: relative;
          padding-top: 20px;
          padding-bottom: 5px;
          cursor: pointer;

          &:hover .slot {
            background-color: rgba(0, 255, 255, 0.9);
          }

          .slot {
            margin-left: -3px;
            width: 14px;
            height: 14px;
            border-radius: 7px;
            background-color: white;
            margin-top: 5px;
            box-shadow: 0 0 4px rgba(0, 0, 0, 0.8);

            &.active {
              background-color: #ff0000 !important;
              transform: scale(1.3);
            }

            &.hasmark {
              background-color: #ffaa00;
            }
          }

          .txt {
            display: flex;
            flex-direction: column;
            margin-left: 8px;
            text-shadow: 0 0 4px rgba(0, 0, 0, 0.8);

            //font-size: vw(18);
            span:nth-child(2) {
              font-size: vw(15);
              font-weight: 600;
              color: #7ed0ff;
            }

            &.active {
              font-size: vw(18);
              margin-left: 10px;
            }
          }
        }
      }

      .zoom_wrap {
        display: flex;
        flex-direction: column;
        position: absolute;
        top: vh(10);
        left: vh(10);
        font-size: vh(25);
        .btn_zoom {
          width: 30px;
          height: 30px;
          font-weight: 600;
          background-color: #ffffff;
          text-align: center;
          margin-top: 5px;
          line-height: 30px;
          box-shadow: 0 0 5px rgba(0, 0, 0, 0.4);
        }
      }

      .img_loading {
        position: absolute;
        height: 100%;
        width: 100%;
        background: rgba(0, 0, 0, 0.5);
        top: 0;
        left: 0;
        z-index: 10;

        > div {
          color: #fff;
          font-size: 36px;
          width: 50px;
          margin: 0 auto;
          padding-top: 30%;
        }
      }
    }

    .content-right {
      margin-top: 0px;
      width: vw(700);
      height: vh(800);
      position: relative;
      color: #cacaca;
      font-size: 15px;
      float: left;
      padding: 0px 10px;
      margin: 0px 20px;

      .mymap {
        width: vw(700);
        height: vh(620);

        position: relative;
        background-color: #008e81;
        margin: 0 auto;
      }

      .txtbox {
        font-size: 20px;
        line-height: 30px;
      }

      .footer {
        width: 500px;
        text-align: center;
        margin-top: 40px;
        font-size: 15px;
        color: #666666;
      }

      .maptab {
        width: 50px;
        height: 50px;
        position: absolute;
        bottom: 120px;
        right: 20px;
        z-index: 99;

        .tab {
          width: 100%;
          height: 100%;
          padding: 2px 5px;
          border-radius: 5px;
          background-color: #fff;
          color: #fff;
          font-size: 18px;
          text-align: center;
          cursor: pointer;
          position: relative;
          box-shadow: 0 0 5px rgba(0, 0, 0, 0.5);

          img {
            height: 40px;
            width: 40px;
          }

          span {
            font-size: 11px;
            color: #ffffff;
            line-height: 20px;
            position: absolute;
            bottom: 0;
            left: 0;
            height: 20px;
            width: 100%;
            background-color: rgba(0, 0, 0, 0.5);
          }
        }
      }
    }
  }

  .close_img_box {
    position: absolute;
    top: 0;
    right: 0;
    width: 40px;
    height: 40px;
    background-color: rgba(0, 0, 0, 0.4);
    color: #ffffff;
    font-size: 25px;
    line-height: 40px;
    text-align: center;
    cursor: pointer;
    text-shadow: 0 1px 0 #fff;
    border-radius: 0px 0 0 2px;
    opacity: 0.5;

    &:hover {
      background-color: rgba(0, 0, 0, 0.95);
    }
  }
}

.popcontent {
  height: vh(800);
}

@media screen and (max-width: 1024px) {
  .aiimgsplan {
    height: 100%;
    overflow-y: auto;
    position: relative;
    background: rgba(5, 34, 74, 0.95);

    .logocontent {
      .logotitle {
        .logotitle_nest {
          font-size: 16px;
        }

        .logotitle_task {
          font-size: 16px;
        }
      }
    }

    .container {
      width: 100%;
      height: auto;
      display: flex;
      flex-direction: column;

      .content {
        width: calc(100% - 30px);
        height: 370px;
        min-height: 370px;
        margin: 15px auto;

        .timelines {
          display: none;
        }

        #canvas {
          width: 100%;
          height: 100%;
        }

        .line {
          display: none;
        }
      }

      .content-right {
        width: 100%;
        height: auto;
        margin: 0 auto;

        .pic_info {
          width: 370px;
          margin: 10px auto;
        }

        .mymap {
          width: 98%;
          height: 400px;
          margin: 0 auto;
        }

        .txtbox {
          font-size: 16px;
          line-height: 20px;
          .qudaohang {
            background-color: #0a95ff;
            border-radius: 10px;
            width: 150px;
            margin: 0 auto;
            height: 40px;
            color: #fff;
            line-height: 40px;
            text-align: center;
          }
        }
      }

      .content-right2 {
        width: 100%;
        height: auto;
      }
    }
  }

  .maskplan {
    position: absolute;
    width: 100%;
    background: rgba(0, 0, 0, 0.5);
    height: 100%;
    top: 0;
    z-index: 9999;
    overflow: hidden;
  }

  .navlist {
    position: absolute;
    width: 100%;
    bottom: 0;
    background: #ffffff;
    z-index: 1000000;

    > div {
      text-align: center;
      height: 60px;
      line-height: 60px;
    }

    > div:first-child {
      border-bottom: 1px solid #eeeeee;
    }
  }
}
</style>

<style type="text/css">
.popitem {
  font-size: 18px;
  color: black;
  text-align: center;
  cursor: pointer;
}

.popitem:hover {
  background-color: #eee;
}
</style>
